<?php
class SiteController extends WikiController {
	var $guest_actions = array(
		'view', 'index', 'image', 'album'
	);
	public function SiteController(){
		parent::WikiController();
	}
	
	public function index(){
		//获取WIKI词汇
		$keyword = $_GET['q'];
		if(!empty($_GET['q'])){
			return $this->wiki($keyword);
		}
		$condition = array('site_id'=>SITE_ID);
		if($_POST['w']){
			$w = $_POST['w']; 
			$condition['word'] = new MongoRegex("/.*".$w.".*/i");
		}
		
		$mod = new DictModel();
		$this->init_page_info();
		$total = $mod->count($condition);
		$this->set_page_total($total);
		if($total>0){
			$dicts = $mod->find($condition, null, $this->page_info->get_start(), 
					$this->page_info->page_size, array('update_time'=>-1));
			$this->assign('dicts', $dicts);
		}
		$this->display();
	}
	
	private function wiki($keyword){
		$mod = new DictModel();
		$dict = $mod->get_by_attrs(array('word'=>$keyword), 'view_count,edit_count,contributors,creator,items,tags,time,word,create_time,update_time');
		$dict['items'] = SortHelper::sortByCol($dict['items'], 'rank', SORT_ASC);
		foreach ($dict['contributors'] as $user=>$count){
			$dict['contributors'][$user] = array(
				'user'=>$user,
				'count' => $count,
			);
		}
		$dict['contributors'] = SortHelper::sortByCol($dict['contributors'], 'count', SORT_DESC);
		
		//图片排序
		foreach ($dict['items'] as &$item){
			if(isset($item['images'])){
				$item['images'] = SortHelper::sortByCol($item['images'], 'rank', SORT_ASC);
				$item['images'] = array_slice($item['images'], 0, 8);
			}
		}
		
		$this->assign(array(
			'wiki' => $dict,
		));
		//更新浏览次数
		if(isset($dict['view_count'])){
			$view_count = ++$dict['view_count'];
		}else{
			$view_count = 1;
		}
		$mod->update_by_key_site_limit($dict['_id'], array('view_count'=>$view_count));
		$this->page_title = $keyword . ' - ' . $this->site_info['name'];
		$this->assign('is_login', !empty($this->user_info));

		$this->page_cached = true;
		
		$this->display('site/view');
	}
	
	public function sort(){
		$ids = $_POST['data'];
		$word = $_REQUEST['q'];
		$ps = explode(';', $ids);
		if(empty($ps)){
			$this->ajax_error('未指定要设置的目录!');
		}
		$mod = new DictModel();
		$dict = $mod->get_by_attrs(array('word'=>$word), 'items');
		if(empty($dict)){
			$this->ajax_error('本词条未找到!');
		}
		$update_attrs = array();
		$rank = 0;
		foreach ($ps as $p){
			if(empty($p))continue;
			++$rank;
			$update_attrs['items.' . $p . '.rank'] = $rank;
		}
		if(empty($update_attrs)){
			$this->ajax_error('无需要更改内容');
		}
		$mod->update_by_key_site_limit($dict['_id'], $update_attrs);

		//保存成功，尝试更新缓存
		$this->clean_wiki_cache($word);
		$this->ajax_info('设置成功！');
	}

	public function add(){
		if(IS_POST){
			$word = self::get_post_val('q');
			self::format($word);
			if(empty($word)){
				$this->error('词条不能为空！');
			}
			$mod = new DictModel();
			if($mod->exists_attrs(array('site_id'=>SITE_ID, 'word'=>$word))){
				$this->error('本词条已经存在！词条：' . $word);
			}
			$tag = self::get_post_val('tag');
			$tags = array();
			if(!empty($tag)){
				$tag_list = preg_split('/[\s|,|.|，|;]/', $tag);
				foreach ($tag_list as $t){
					$new_t = trim($t);
					if(!empty($new_t)){
						$tags[$new_t] = 1;
					}
				}
			}
			$user_name = $this->user_info['user_name'];
			$dict_cate = $_POST['dict_cate'];
			$dict = array(
				'author' => $user_name,
				'contributors' => array(
					$user_name => 1,
				),
				'create_time' => time(),
				'creator' => $user_name,
// 				'history' => array(),
				'site_id' => SITE_ID,
				'tags' => $tags,
				'update_time' => time(),
				'view_count' => 1,
				'edit_count' => 1,
				'word' => $word,
				'cate' => $dict_cate
			);
			$ps = $_POST['p'];
			$ps = array_unique($ps);
// 			$contents = $_POST['content'];
			$i = 1;
			$available_index = 0;
			$time = time();
			foreach($ps as $new_p){
				self::format($new_p);
				if(empty($new_p)){
					++$i;
					continue;
				}
				$dict['items'][$new_p] = array(
					'author' => $user_name,
					'content' => '',
					'rank' => $i,
					'time' => $time,
				);
				++$i;
// 				++$available_index;
			}
			$mod->insert($dict);
			//用户记数添加
			$user_mod = new UserModel();
			$user_mod->inc($this->user_info['_id'], array(
				'wiki' => 1,
// 				'wiki_index' => $available_index,
			));
			$this->redirect('/wiki/' . $word);
		}
		$this->page_title = '添加词条 - ' . $this->site_info['name'];
		
		$this->assign('cates', self::get_cate_options());
		$default_cates = require_once ROOT_PATH . '/protected/web/wiki/dict_config.php';
		$this->assign('default_indexs', $default_cates);
		$this->display();
	}
	
	private function get_cate_options(){
		$mod = new DictCateModel();
		$dict_cates = $mod->get_by_key(SITE_ID);
		unset($dict_cates['_id']);
		$tree = new Tree($dict_cates);
		return $tree->get_options('　');
	}

	public function check_word(){
		$word = $_POST['q'];
		$mod = new DictModel();
		if($mod->exists_attrs(array('site_id'=>SITE_ID, 'word'=>$word))){
			echo 'false';
			return;
		}else{
			echo 'true';
			return;
		}
	}
	
	public function edit(){
		$word = $_REQUEST['q'];
echo $word;
		//获取WIKI词汇
		$mod = new DictModel();
		$dict = $mod->get_by_attrs(array('word'=>$word), 'contributors,edit_count,tags,content,time,word,items,author,cate');
		$opts = self::get_cate_options();
		$this->assign('cates', $opts);
		$this->assign('wiki', $dict);
		$this->page_title = $dict['word'] . '-修改 -WIKI-' . $this->site_info['name'];
		
		$this->display();
	}
	
	public function edit_item(){
		$word = $_REQUEST['q'];
		self::format($word);
		$p = urldecode($_REQUEST['p']);
		self::format($p);
		
		//获取WIKI词汇
		$mod = new DictModel();
		$dict = $mod->get_by_attrs(array('word'=>$word), 'contributors,edit_count,content,time,word,items.' . $p . ',author,cate,history.' . $p);
		$item = $dict['items'][$p];	
		if(isset($_GET['h'])){
			$h = $_GET['h'];
		}
		if(IS_POST && !empty($p)){
			$time = time();
			$is_new = false;
			if(isset($_POST['is_new'])){
				$is_new = true;
			}
			$user_name = $this->user_info['user_name'];
			
			$updated = false;
			$content = $_POST['content'];
			$new_attrs = array();
			if($item['content'] != $content){
				//编辑次数
				if(isset($dict['edit_count'])){
					$edit_count = ++$dict['edit_count'];
				}else{
					$edit_count = 1;
				}
				
				$new_attrs = array(
					'items.'.$p . '.content' => $content,
					'items.'.$p . '.author' => $user_name,
					'items.'.$p . '.time' => $time,
					'update_time' => $time,
					'edit_count' => $edit_count,
				);
				
				if(!$is_new && isset($item['time']) && !empty($item['content'])){
					//处理旧版本
					$new_history = array(
						'content' => $item['content'],
						'time' => $item['time'],
						'author' => $item['author'],
					);
					$new_attrs['history.'.$p.'.'.$item['time']] = $new_history;
				}
				
				if(array_key_exists($user_name, $dict['contributors'])){
					//已经存在
					$count = $dict['contributors'][$user_name];
				}else{
					$count = 1;
				}
	
				$new_attrs['contributors.' . $user_name] = $count;
				$updated = true;
			}
			
			if(isset($_POST['imgs'])){
				$updated = true;
				$imgs = $_POST['imgs'];
				foreach ($imgs as $img){
					$file = ROOT_PATH . $img;
					if(!is_file($file))continue;
					$arr=getimagesize($file);
					$size = filesize($file);
					$img_mod = new ImageModel();
					$img_id = gen_guid();
					$img_mod->insert(array(
						'_id' => $img_id,
						'file' => $img,
						'width' => $arr[0],
						'height' => $arr[1],
						'size' => $size,
						'author' => $user_name,
						'collect' => 0,
						'create_time' => $time,
						'desc' => '',
						'title' => $word . '-' . $p,
						'from' => '/wiki/' . $word . '#' . $p,
						'hate' => 0,
						'like' => 0,
						'site_id' => SITE_ID,
					));
					$mod->update_by_key_site_limit($dict['_id'], array('items.'.$p.'.images.' . $img_id => array(
						'file' => $img,
						'author' => $user_name,
						'time' => $time,
						'count' => 1,
						'rank' => 1000,
					)));
				}
				//用户记数添加
				$user_mod = new UserModel();
				$user_mod->inc($this->user_info['_id'], array(
					'image'=> count($imgs),
					'wiki_index' => 1
				));
			}
			
			if(isset($_POST['refers'])){
				$refers = $_POST['refers'];
				if($refers!=null && count($refers)>0){
					$updated = true;
					foreach ($refers as $refer){
						$mod->push($dict['_id'], 'items.'.$p.'.refers', array(
							'word' => $refer,
							'rank' => 100
						));
					}
				}
			}
			
			if(!$updated){
				$this->assign('error', '内容没有更新！');
			}else{
				$new_attrs['update_time'] = $time;
				$mod->update_by_key_site_limit($dict['_id'], $new_attrs);
				//保存成功，尝试更新缓存
				$this->clean_wiki_cache($word);
				$this->redirect('/wiki/' . $word);
				exit;
			}
			
			
		}
		$this->page_title = $word . '-词条修改-' . $this->site_info['name'];
		
		//筛选出尚未添加的词条给予备选
		$cate = $dict['cate'];
		$default_indexs = $this->getDefaultIndex($cate);
		foreach ($default_indexs as $i=>$index_config){
			if(array_key_exists($index_config['name'], $dict['items'])){
				unset($default_indexs[$i]);
			}
		}
		$this->assign('default_indexs', $default_indexs);
		
		//$dict['items'] = SortHelper::sortByCol($dict['items'], 'rank', SORT_ASC);
		foreach ($dict['contributors'] as $user=>$count){
			$dict['contributors'][$user] = array(
					'user'=>$user,
					'count' => $count,
			);
		}
		$dict['contributors'] = SortHelper::sortByCol($dict['contributors'], 'count', SORT_DESC);
		if(isset($item['images'])){
			$item['images'] = SortHelper::sortByCol($item['images'], 'rank', SORT_ASC);
			$item['image_count'] = count($item['images']);
			$item['images'] = array_slice($item['images'], 0, 8);
		}else{
			$item['image_count'] = 0;
		}
		if(isset($h)){
			$item['content'] = $dict['history'][$p][$h]['content'];
		}
		$this->assign(array(
			'wiki' => $dict,
			'item' => $item,
			'item_title' => $p,
			'history' => SortHelper::sortByCol($dict['history'][$p], 'time', SORT_DESC),
		));
		$this->display();
	}
	
	public function add_refer(){
		$word = $_POST['word'];
		$dict_mod = new DictModel();
		if($dict_mod->exists_attrs(array('site_id'=>SITE_ID, 'word'=>$word))){
			if($dict_mod->exists_attrs(array('site_id'=>SITE_ID, 'refers.word'=>$word))){
				$this->ajax_error('本词条已添加到相关词条！');
			}
			$this->ajax_info('词条存在！');
		}else{
			$this->ajax_error('词条不存在：' . $word);
		}
	}
	
	public function set_available_index(){
		$word = $_GET['q'];
		$index = urldecode($_GET['p']);
		//获取WIKI词汇
		$mod = new DictModel();
		if(!$mod->exists_column(array('site_id'=>SITE_ID, 'word'=>$word), 'items.' . $index)){
			$this->ajax_error('您要删除的目录已被删除或不存在！');
		}
		$condition = array('site_id'=>SITE_ID, 'word'=>$word);
		$dict = $mod->get_by_attrs($condition, 'items.' . $index);
		if(isset($dict['items'][$index]['available'])){
			if($dict['items'][$index]['available'] === false){
				$mod->update_by_attrs($condition, array('items.' . $index.'.available'=>true));
				$this->clean_wiki_cache($word);
				$this->ajax_info('恢复成功！');
			}
		}
		$mod->update_by_attrs($condition, array('items.' . $index.'.available'=>false));
		$this->clean_wiki_cache($word);
		
		$this->ajax_info('删除成功！');
	}
	
	public function album(){
		$word = $_REQUEST['q'];
		$tpl = 'album';
		$columns = 'view_count,edit_count,contributors,author,items,tags,time,word,create_time,update_time';
		$this->page_title = '图片专辑 - ' . $word;
		if(isset($_REQUEST['p'])){
			$tpl = 'album_sub';
			$p = urldecode($_REQUEST['p']);
			$this->assign('p', $p);
			$this->page_title .= ' - ' . $p;
			$columns = 'view_count,edit_count,contributors,author,items.'.$p.'.images,tags,time,word,create_time,update_time';
			
			$page_size = 120;
			$this->init_page_info($page_size);
			//获取分页数据
			if(isset($_GET['page'])){
				$page = intval($_GET['page']);
			}else{
				$page = 1;
			}
			if($page<=0)$page = 1;
			$this->assign('page_size', $page_size);
			$this->assign('start', ($page - 1) * $page_size);
		}
		$this->page_title .= ' - ' . $this->site_info['name'];
		
		$mod = new DictModel();
		$dict = $mod->get_by_attrs(array('word'=>$word), $columns);
		if($tpl === 'album'){
			$dict['items'] = SortHelper::sortByCol($dict['items'], 'rank', SORT_ASC);
			//图片排序
			foreach ($dict['items'] as &$dict_indexs){
				if(isset($dict_indexs['images'])){
					$dict_indexs['images'] = SortHelper::sortByCol($dict_indexs['images'], 'rank', SORT_ASC);
					$dict_indexs['image_count'] = count($dict_indexs['images']);
					$dict_indexs['images'] = array_slice($dict_indexs['images'], 0, 12);
				}
			}
		}else{
			$total = 0;
			if(isset($dict['items'][$p]['images'])){
				$index_images = &$dict['items'][$p]['images'];
				$total = count($index_images);
				$index_images = SortHelper::sortByCol($index_images, 'rank', SORT_ASC);
			}
			$this->set_page_total($total);
		}
		foreach ($dict['contributors'] as $user=>$count){
			$dict['contributors'][$user] = array(
				'user'=>$user,
				'count' => $count,
			);
		}
		$dict['contributors'] = SortHelper::sortByCol($dict['contributors'], 'count', SORT_DESC);
		$this->assign(array(
			'wiki' => $dict,
		));
// 		echo $tpl;exit;
		$this->display('site/' . $tpl);
	}
	
	public function image(){
		$word = $_REQUEST['q'];
		$p = urldecode($_REQUEST['p']);
		$i = trim($_GET['i']);
		$mod = new DictModel();
		$dict = $mod->get_by_attrs(array('word'=>$word), 'contributors,edit_count,content,time,word,items,author');
		$item = $dict['items'][$p];	
		$img = $dict['items'][$p]['images'][$i];
		$this->page_title = '图片视图 - ' . $p . '-' . $word  . ' - ' . $this->site_info['name'];
		//分析图片规格
		$image_mod = new ImageModel();
		$image_info = $image_mod->get_by_key_site_limit($i);
		$this->assign(array(
			'index' => $p,
			'wiki' => $dict,
			'image' => $img,
			'image_info' => $image_info,
		));
		$this->display();
	}
	
	private function clean_wiki_cache($word){
		//保存成功，尝试更新缓存
		$this->update_page_cache('/sites/main/' . MAIN_DOMAIN . '/html/wiki/' . $word);
	}
	
	/**
	 * 格式化词条，将.换成全角的点号
	 * @param unknown_type $word
	 */
	private function format(&$word){
		$word = preg_replace('/\./', '．', $word);
		$word = trim($word);
		return $word;
	}
	
	private function getDefaultIndex($cate){
		$default_cates = require_once ROOT_PATH . '/protected/web/wiki/dict_config.php';
		if(array_key_exists($cate, $default_cates)){
			return $default_cates[$cate];
		}
		return array(array('name'=>'概要介绍'));
	}
	
	/**
	 * 检查词条条目是否已经存在
	 */
	public function check_word_index(){
		$word = trim($_POST['word']);
		$index = trim($_POST['index']);
		$mod = new DictModel();
		if($mod->exists_column(array('site_id'=>SITE_ID, 'word'=>$word), 'items.' . $index)){
			echo 'false';
		}else{
			echo 'true';
		}
	}
}

?>